<?php

namespace app\api\controller;

use think\cache\driver\Redis;
use Pheanstalk\Pheanstalk;
use think\Log;

// 发送模板消息
class Xcxtmp extends Base
{

    public $redis;
    public $ser;
    public $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

    // 开启监听
    public function start()
    {
        echo 'start';
        $this->ser = new Pheanstalk('127.0.0.1');
        $this->redis = new Redis($options = ['select' => 'sendtmp', 'persistent' => true]);
        set_time_limit(0);

        while (1) {
            $job = $this->ser->watch('xcx_tmp')->ignore('default')->reserve(); // 监听管道
            $data = json_decode($job->getData(), true);
            $this->send_msg($data);
            $this->ser->delete($job);
            usleep(100);
        }
    }

    // 发送消息
    public function send_msg($data)
    {
        $appid = $data['appid'];
        $secret = $data['secret'];
        $openid = $data['openid'];
        $formid = $data['formid'];
        $tmp = $data['tmp'];

        if ($openid) {
            $token = $this->get_access_token($appid, $secret);
            if ($token) {
                $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' . $token;
                $templateData = $this->create_template($openid, $tmp, $formid);//拼接模板数据
                $res = json_decode($this->http($url, $templateData, 'POST', $this->headers));
                if ($res->errcode == 0) {
                    return true;
                } else {
                    Log::error($openid . ":");
                    Log::error($res);
                    return false;
                }
            } else {
                Log::error('token获取失败');
                return false;
            }
        }
    }

    // 拼装模板，创建通知内容
    private function create_template($openId, $tmp, $formId)
    {
        foreach ($tmp['data'] as $k => $v) {
            $templateData[$k]['value'] = $v;
        }
        $data['emphasis_keyword'] = 'keyword1.DATA';
        $data['touser'] = $openId;
        $data['template_id'] = $tmp['template_id'];
        $data['page'] = $tmp['page'];
        $data['form_id'] = $formId;
        $data['data'] = $templateData;
        return json_encode($data);
    }

    // 调用微信api，获取access_token，有效期7200s
    public function get_access_token($appid, $secret)
    {
        // 在有效期，直接返回access_token
        if ($this->redis->has($appid)) {
            return $this->redis->get($appid);
        } else {
            // 不在有效期，重新发送请求，获取access_token
            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            $params['grant_type'] = 'client_credential';
            $params['appid'] = $appid;
            $params['secret'] = $secret;

            $result = $this->http($url, $params);
            $res = json_decode($result, true);   //json字符串转数组

            if (array_key_exists('access_token', $res)) {
                $this->redis->set($appid, $res['access_token'], 7100);
                return $res['access_token'];
            } else {
                return false;
            }
        }
    }
}

$server = new Xcxtmp();
$server->start();